//
//  MusicPlayViewController.m
//  A_Project_DLS151129_SQ
//
//  Created by 151129-49宋强 on 16/1/21.
//  Copyright © 2016年 www.lanou3g.com蓝鸥. All rights reserved.
//

#import "MusicPlayViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "Player.h"


@interface MusicPlayViewController ()
@property (nonatomic, retain) AVPlayer *avPlayer;//播放器对象
@property (nonatomic, retain) AVPlayerItem *playerItem;//播放对象
@property (nonatomic, retain) NSString *musicUrl;
@property (nonatomic, assign) BOOL isPlay;
@property (nonatomic, retain) UISlider *progress;
@property (nonatomic, retain) UILabel *timeLabel;
@property (nonatomic, assign) CGFloat totalDuration;
@property (nonatomic, retain) NSNumber *like;
@property (nonatomic, retain) NSNumber *comment;
@property (nonatomic, retain) NSString *contentId;
@property (nonatomic, assign) BOOL isLike;
@end

@implementation MusicPlayViewController

- (void)dealloc
{   [[NSNotificationCenter defaultCenter] removeObserver:self name:@"是否播放" object:nil];
    [_comment release];
    [_like release];
    [_contentId release];
    [_avPlayer release];
    [_playerItem release];
    [_musicUrl release];
    [_progress release];
    [_timeLabel release];
    [_mm release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //数据处理
    [self dataHandle];
    //图片和label
    [self creatImageViewAndLabel];
    //初始化时间显示
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(Width - 110, HEIGHT - 150, 100, 30)];
    [self.view addSubview:_timeLabel];
    [_timeLabel release];
    _timeLabel.text = @"00:00/00:00";
    //初始化进度条
    self.progress = [[UISlider alloc] initWithFrame:CGRectMake(10, HEIGHT - 150, Width - 100 - 20 - 10, 30)];
    [self.view addSubview:_progress];
    [_progress release];
    _progress.value = 0;
    [_progress addTarget:self action:@selector(progressAction:) forControlEvents:UIControlEventValueChanged];
}
- (void)creatBtn
{
    UIButton *commentBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    commentBtn.frame = CGRectMake(50, HEIGHT - 200, 30, 30);
    [commentBtn addTarget:self action:@selector(commentAction) forControlEvents:UIControlEventTouchUpInside];
    [commentBtn setImage:[UIImage imageNamed:@"commet.png"] forState:UIControlStateNormal];
    [self.view addSubview:commentBtn];
    UILabel *commentLabel = [[UILabel alloc] initWithFrame:CGRectMake(50 + 30 + 5, commentBtn.frame.origin.y, 80, 30)];
    commentLabel.text = [self.comment stringValue];
    [self.view addSubview:commentLabel];
    [commentLabel release];
    UIButton *xinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [xinBtn addTarget:self action:@selector(xinAction:) forControlEvents:UIControlEventTouchUpInside];
    xinBtn.frame = CGRectMake(Width - 100 - 5, commentBtn.frame.origin.y, 30, 30);
    [xinBtn setImage:[UIImage imageNamed:@"xin.png"] forState:UIControlStateNormal];
    [self.view addSubview:xinBtn];
    UILabel *xinLabel = [[UILabel alloc] initWithFrame:CGRectMake(xinBtn.frame.origin.x + 30 + 5, commentBtn.frame.origin.y, 80, 30)];
    xinLabel.text = [self.like stringValue];
    [self.view addSubview:xinLabel];
    [xinLabel release];
   }
#pragma mark - 跳转评论页
- (void)commentAction
{
    CommentViewController *commentVC = [[CommentViewController alloc] init];
    commentVC.contenid = self.contentId;
    [self.navigationController pushViewController:commentVC animated:YES];
    [commentVC release];
}
- (void)xinAction:(UIButton *)btn
{
    if (!_isLike) {
        [btn setImage:[UIImage imageNamed:@"hongxin.png"] forState:UIControlStateNormal];
    }else{
        [btn setImage:[UIImage imageNamed:@"xin.png"] forState:UIControlStateNormal];
    }
    _isLike = !_isLike;
}
#pragma mark - 手动进度控制
- (void)progressAction:(UISlider *)slider
{
    [_avPlayer pause];
    //当前时间
    CGFloat current = slider.value * _totalDuration;
    //创建CMTime
    CMTime time = CMTimeMake(current, 1);
    //把time赋值给播放器 跳转到对应的时间点
    [_avPlayer seekToTime:time completionHandler:^(BOOL finished) {
        [_avPlayer play];
    }];

}
#pragma mark - 进度条监听
- (void)progressObserving
{
    //设置(1, 1)每秒刷新一次
    //参数1:事件监听器 刷新时间
    //参数2:队列
    //参数3:刷新时执行的block
    __block MusicPlayViewController *vc = self;
    [ _avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        //获取总时长
        CGFloat duration = CMTimeGetSeconds(vc.playerItem.duration);
        //获取当前时长
        CGFloat current = CMTimeGetSeconds(vc.avPlayer.currentTime);
        //获取倒计时
        CGFloat rem = duration - current;
        //剩余时间
        NSString *totalt = [NSString stringWithFormat:@"%02d:%02d", (int)rem / 60, (int)rem % 60];
        //当前时间
        NSString *currentT = [NSString stringWithFormat:@"%2d:%2d", (int)current / 60, (int)current % 60];
        //拼接时间
        NSString *timerStr = [NSString stringWithFormat:@"%@/%@",currentT, totalt];
        vc.timeLabel.text = timerStr;
        //保存总时长 用于slider手动控制进度
        vc.totalDuration = duration;
        //控制slider的当前进度
        vc.progress.value = current / duration;
    }];

}
#pragma mark - 通知中心
- (void)addNotificationCenter
{
    //是否播放完成
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(moviePlayDidEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

}
- (void)moviePlayDidEnd:(NSNotificationCenter *)noti
{
    NSLog(@"视频播放已经结束");
}

//初始化播放器方法
- (void)creatAVplayer
{
    //音频网址
    NSURL *url = [NSURL URLWithString:_musicUrl];
  //  NSLog(@"%@",_musicUrl);
    //创建播放对象
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    //创建播放器对象
     self.avPlayer = [Player shareInstance:_playerItem];
    [self.avPlayer play];
    //通过通知中心 监听  状态信息
    [self addNotificationCenter];
    //进度条监听
    [self progressObserving];
#pragma mark - 注册通知中心
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(playAction:) name:@"是否播放" object:nil];
    
}
#pragma mark - 通过通知中心判断是否开始播放
- (void)playAction:(NSNotification *)noti
{
    if ([[noti.userInfo objectForKey:@"playInfo"] isEqualToString:@"1"]) {
        [self.avPlayer play];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPlay"];
    }else{
        [self.avPlayer pause];
         [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPlay"];
    }
    
}
- (void)creatImageViewAndLabel
{
    UIImageView *imgView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 50, self.view.frame.size.width - 100, 250)];
    [imgView sd_setImageWithURL:[NSURL URLWithString:_mm.coverimg] placeholderImage:[UIImage imageNamed:@"coffe.png"]];
    [self.view addSubview:imgView];
    [imgView release];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 310, self.view.frame.size.width - 100, 50)];
    titleLabel.font = [UIFont boldSystemFontOfSize:20];
    titleLabel.text = _mm.title;
    [self.view addSubview:titleLabel];
    [titleLabel release];
    //暂停图片
    UIImageView *stopView = [[UIImageView alloc] initWithFrame:CGRectMake((375 - 60) / 2, 400, 60, 60)];
    stopView.tag = 1000;
    stopView.userInteractionEnabled = YES;
    [self.view addSubview:stopView];
    [stopView release];
    stopView.image = [UIImage imageNamed:@"kaishi.png"];
    //创建button
    UIButton *playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    playBtn.frame = CGRectMake(0, 0, 60, 60);
    [stopView addSubview:playBtn];
    [playBtn addTarget:self action:@selector(btn:) forControlEvents:UIControlEventTouchUpInside];
    
}
//点击改变图片
- (void)btn:(UIButton *)button
{
    if (!button.selected) {
        UIImageView *imgView = [self.view viewWithTag:1000];
        imgView.image = [UIImage imageNamed:@"zanting.png"];
        [self.avPlayer pause];
     [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isPlay"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"播放" object:@"暂停" userInfo:nil];
    }else{
        UIImageView *imgView = [self.view viewWithTag:1000];
        imgView.image = [UIImage imageNamed:@"kaishi.png"];
         [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"isPlay"];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"播放" object:@"开始" userInfo:nil];
        [self.avPlayer play];
          }

   //状态反转
    button.selected = !button.selected;
}

//数据处理
- (void)dataHandle
{
    NSString *urlStr = @"http://api2.pianke.me/ting/info";
    NSDictionary *dic = @{@"client:":@2,@"tingid":self.mm.tingid};
    [PWNetWorking POSTWithURL:urlStr body:dic completion:^(id result) {
       self.musicUrl = result[@"data"][@"playInfo"][@"musicUrl"];
        //初始化播放器
        [self creatAVplayer];
        self.like = result[@"data"][@"like"];
        self.comment = result[@"data"][@"comment"];
        self.contentId = result[@"data"][@"ting_contentid"];
        //创建评论和喜欢按钮
        [self creatBtn];
    }];
    
    
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
